<template>
  <div v-if="isLogin" class="chat-assistant"
       :class="{ 'minimized': isMinimized, 'fullscreen': isFullscreen, 'exit-fullscreen': isExitingFullscreen }">
    <!-- 头部保持不变 -->
    <div class="chat-header" @click="toggleMinimize">
      <span v-if="!isMinimized">聊天助手</span>

      <div class="header-icons" v-if="!isMinimized">
        <el-icon v-if="!isFullscreen" @click.stop="enterFullscreen">
          <FullScreen />
        </el-icon>

        <el-icon v-if="isFullscreen" @click.stop="exitFullscreen">
          <Crop />
        </el-icon>

        <el-icon>
          <component :is="isMinimized ? 'ArrowUp' : 'ArrowDown'" />
        </el-icon>

      </div>

    </div>

    <div class="chat-body" v-show="!isMinimized">
      <!-- 消息区域保持不变 -->
      <div class="chat-messages" ref="chatMessages">
        <div v-for="(message, index) in messages" :key="index"
             :class="['message', message.type === 'user' ? 'user-message' : 'assistant-message']">
          <!-- 修改用户消息渲染方式，使用v-html和renderMarkdown -->
          <div v-if="message.type === 'user'" class="user-content">
            <div v-html="renderMarkdown(message.content)" class="md-body user-md-body"></div>

          </div>

          <div v-else class="assistant-content">
            <div v-html="renderMarkdown(message.content)" class="md-body"></div>

          </div>

          <div v-if="message.status === 'error'" class="message-actions">
            <el-button type="primary" link size="small" @click="retryMessage(index)">
              <el-icon>
                <Refresh />
              </el-icon>重试
            </el-button>

          </div>

        </div>

      </div>

      <div class="chat-input">
        <!-- 添加知识库开关和其他开关 -->
        <div class="knowledge-switch" v-if="!isMinimized">
          <span>本地知识库</span>

          <el-switch v-model="useLocalKnowledge" active-color="#409EFF" inactive-color="#909399">
          </el-switch>

          <span style="margin-left: 15px;">历史对话</span>

          <el-switch v-model="useHistoryChat" active-color="#409EFF" inactive-color="#909399">
          </el-switch>

          <span style="margin-left: 15px;">内置工具</span>

          <el-switch v-model="useTools" active-color="#409EFF" inactive-color="#909399">
          </el-switch>

        </div>

        <!-- 添加图片预览区域 -->
        <div v-if="imageList.length > 0" class="image-preview-container">
          <div v-for="(image, index) in imageList" :key="index" class="image-preview-item">
            <img :src="image.url" class="preview-image" />
            <el-icon class="remove-icon" @click="removeImage(index)">
              <Close />
            </el-icon>

          </div>

        </div>

        <!-- 快捷操作区域 -->
        <div class="quick-actions" v-if="!isMinimized">
          <el-button size="small" link @click="askQuestion('查看课表')">查看课表</el-button>

          <el-button size="small" link @click="askQuestion('作业辅导')">作业辅导</el-button>

          <el-button size="small" link @click="askQuestion('学习资源')">学习资源</el-button>

          <el-button size="small" link @click="askQuestion('考试辅导')">考试辅导</el-button>

        </div>

        <!-- 输入框添加粘贴事件 -->
        <el-input v-model="inputMessage" placeholder="请输入消息...(可Ctrl+V粘贴图片)" @keyup.enter="sendMessage"
                  @paste="handlePaste">
          <template #append>
            <el-button @click="sendMessage">
              <el-icon>
                <Promotion />
              </el-icon>

            </el-button>

          </template>

        </el-input>

      </div>

    </div>

  </div>

</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onBeforeUnmount, onMounted } from 'vue'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { getToken } from "@/utils/auth"
import useUserStore from '@/store/modules/user'
import { FullScreen, Crop, ArrowUp, ArrowDown, Refresh, Promotion, Close } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
// 修改导入，使用request.js中的upload方法
import { upload } from '@/utils/request'
// 将Cookies导入移到顶部
import Cookies from "js-cookie"
import { useEventBus } from '@/utils/eventBus'

// 初始化markdown-it
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (__) { }
    }
    return '' // 使用默认的转义
  }
})

// 渲染markdown内容
const renderMarkdown = (content) => {
  return md.render(content || '')
}

// 状态管理
const userStore = useUserStore()
const isLogin = ref(!!getToken())
const sseSource = ref(null)
const isMinimized = ref(true)
const isFullscreen = ref(false)
const isExitingFullscreen = ref(false)
const inputMessage = ref("")
const messages = ref([
  {
    type: "assistant",
    content: "您好！我是雅橙学习助手，有什么可以帮助您的吗？",
    status: "success"
  }
])
const requestTimeout = ref(null)
const timeoutDuration = 30000 // 超时时间，默认30秒
const chatMessages = ref(null)

// 只添加知识库开关
const useLocalKnowledge = ref(true) // 本地知识库开关，默认开启

const useHistoryChat = ref(true) // 历史对话开关，默认开启
const useTools = ref(true) // 工具调用开关，默认开启
const imageList = ref([]) // 存储待上传的图片列表
const websock = ref(null)

// 监听 token 变化
watch(() => userStore.token, (newVal) => {
  const newLoginState = !!newVal;
  // 只有当登录状态从未登录变为已登录时，才初始化欢迎消息
  if (newLoginState && !isLogin.value) {
    initWebSocket();
    initWelcomeMessage();
  }
  isLogin.value = newLoginState;
})

// 切换最小化状态
const toggleMinimize = () => {
  // 如果当前是全屏状态，先退出全屏到展开状态
  if (isFullscreen.value) {
    exitFullscreen()
    return
  }

  // 否则在最小化和展开之间切换
  isMinimized.value = !isMinimized.value
}

// 进入全屏状态（只能从展开状态进入）
const enterFullscreen = () => {
  if (!isMinimized.value && !isFullscreen.value) {
    isFullscreen.value = true
  }
}

// 退出全屏状态（回到展开状态）
const exitFullscreen = () => {
  if (isFullscreen.value) {
    isExitingFullscreen.value = true
    setTimeout(() => {
      isFullscreen.value = false
      isExitingFullscreen.value = false
    }, 300) // 动画持续时间
  }
}

// 处理粘贴事件
const handlePaste = (event) => {
  const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      const blob = items[i].getAsFile();
      const reader = new FileReader();
      reader.onload = (e) => {
        imageList.value.push({
          file: blob,
          url: e.target.result
        });
      };
      reader.readAsDataURL(blob);
    }
  }
}

// 移除图片
const removeImage = (index) => {
  imageList.value.splice(index, 1);
}

// 修改发送消息方法，确保异步处理正确
const sendMessage = async () => {
  if (!inputMessage.value.trim() && imageList.value.length === 0) return;

  let messageContent = inputMessage.value.trim();
  let imageUrls = [];

  // 上传图片（如果有）
  if (imageList.value.length > 0) {
    try {
      // 上传所有图片
      const uploadPromises = imageList.value.map(image => {
        return upload('/file/upload', image.file);
      });

      const results = await Promise.all(uploadPromises);
      // 提取图片URL
      imageUrls = results.map(res => {
        return res.url || (res.data && res.data.url) || '';
      }).filter(url => url); // 过滤掉空URL

      // 清空图片列表
      imageList.value = [];

      // 如果有成功上传的图片，添加到消息内容中
      if (imageUrls.length > 0) {
        const imageMarkdown = imageUrls.map(url => `![图片](${url})`).join('\n');
        messageContent = messageContent ? `${messageContent}\n\n${imageMarkdown}` : imageMarkdown;
      }
    } catch (error) {
      console.error('上传图片失败:', error);
    }
  }

  // 添加用户消息
  messages.value.push({
    type: "user",
    content: messageContent,
    status: "success"
  });

  inputMessage.value = "";

  // 添加助手消息（初始状态为loading）
  messages.value.push({
    type: "assistant",
    content: "正在思考...",
    status: "loading"
  });

  // 获取助手回复
  const messageIndex = messages.value.length - 1;
  getAssistantResponse(messageContent, messageIndex);

  // 滚动到底部
  nextTick(() => {
    if (chatMessages.value) {
      chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
    }
  });
}
// 初始化WebSocket
const initWebSocket = () => {
  let fromId = Cookies.get("usernameForIM");
  if (!fromId) {
    return;
  }

  // 修复WebSocket URL的构建方式
  let baseUrl = '';
  try {
    // 尝试使用Vue3的环境变量
    baseUrl = import.meta.env.VITE_APP_BASE_API || '';
  } catch (e) {
    // 如果失败，尝试使用Vue2的环境变量
    baseUrl = process.env.VUE_APP_BASE_API || '';
  }

  // 确保baseUrl不为空
  if (!baseUrl) {
    console.error('无法获取API基础URL');
    return;
  }

  // 构建WebSocket URL
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const wsHost = "localhost:8080"
  const wsuri = `${wsProtocol}//${wsHost}/ai/ws/${fromId}`;

  console.log('WebSocket连接URL:', wsuri);

  websock.value = new WebSocket(wsuri);
  websock.value.onmessage = websocketonmessage;
  websock.value.onopen = websocketonopen;
  websock.value.onerror = websocketonerror;
  websock.value.onclose = websocketclose;
}
// WebSocket相关方法
const websocketonopen = () => {
  // 连接建立之后执行send方法发送数据
  console.log("WebSocket连接成功");
}

const websocketonerror = () => {
  // 连接建立失败重连
  console.log("WebSocket连接失败，正在重连...");
  setTimeout(() => initWebSocket(), 20000);
}

// 添加欢迎消息初始化方法
const initWelcomeMessage = () => {
  let userMessage = "你是雅橙智能助手，根据我的信息动态生成欢迎消息,并简洁生成一些学习建议";
  // 添加助手消息（初始状态为loading）
  messages.value = [{
    type: "assistant",
    content: "雅橙助手正在初始化...",
    status: "loading"
  }];
  // 获取助手回复
  const messageIndex = messages.value.length - 1;
  getAssistantResponse(userMessage, messageIndex);
}

// 添加操作处理方法
const handleOperation = (operation, params) => {
  // 记录操作到聊天窗口
  addAssistantMessage(`正在执行操作: ${operation}`);

  // 触发全局操作事件
  const eventBus = useEventBus();
  eventBus.emit('operation', {
    type: operation,
    params: params,
    callback: (result) => {
      // 操作完成后的回调，将结果显示在聊天窗口
      if (result.success) {
        addAssistantMessage(`操作成功: ${result.message || '操作已完成'}`);
      } else {
        addAssistantMessage(`操作失败: ${result.message || '未知错误'}`);
      }
    }
  });
}
// 修改 WebSocket 消息处理方法
const websocketonmessage = (e) => {
  const data = e.data;
  // 判断是否是JSON格式
  try {
    const jsonData = JSON.parse(data);
    // 如果是JSON格式，根据消息类型处理
    if (jsonData.type === 'navigation') {
      // 导航类型消息，触发全局事件
      const eventBus = useEventBus();
      eventBus.emit('navigation', jsonData.path);
    } else if (jsonData.type === 'chat') {
      // 聊天类型消息，显示在聊天窗口
      addAssistantMessage(jsonData.content);
    } else if (jsonData.type === 'operation') {
      // 操作类型消息，执行特定操作
      handleOperation(jsonData.operation, jsonData.params);
    }
  } catch (error) {
    console.error('解析WebSocket消息失败:', error);
  }
}


const websocketclose = (e) => {
  console.log('WebSocket断开连接', e);
  setTimeout(() => initWebSocket(), 20000);
}

// 添加助手消息方法
const addAssistantMessage = (content) => {
  messages.value.push({
    type: "assistant",
    content: content,
    status: "success"
  });

  // 滚动到底部
  nextTick(() => {
    if (chatMessages.value) {
      chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
    }
  });
}

// 组件挂载时初始化WebSocket
onMounted(() => {
  initWebSocket();
  initWelcomeMessage();
})

// 组件销毁时关闭WebSocket
onBeforeUnmount(() => {
  if (requestTimeout.value) {
    clearTimeout(requestTimeout.value)
  }
  if (sseSource.value) {
    sseSource.value.close()
  }
  if (websock.value) {
    websock.value.close()
  }
})
// 快捷问题方法
const askQuestion = (type) => {
  let question = ""
  switch (type) {
    case "查看课表":
      question = "请介绍一下本周课表"
      break
    case "作业辅导":
      question = "我在作业中遇到了困难，能提供一些指导吗？"
      break
    case "学习资源":
      question = "有哪些推荐的学习资源？"
      break
    case "考试辅导":
      question = "如何准备即将到来的考试？"
      break
    default:
      question = "您好，我需要帮助"
  }

  inputMessage.value = question
  sendMessage()
}

// 重试消息方法
const retryMessage = (index) => {
  const message = messages.value[index]
  // 找到这条消息之前的用户消息
  let userMessageIndex = index - 1
  while (userMessageIndex >= 0) {
    if (messages.value[userMessageIndex].type === 'user') {
      break
    }
    userMessageIndex--
  }

  if (userMessageIndex >= 0) {
    const userMessage = messages.value[userMessageIndex].content
    // 更新当前消息状态
    messages.value[index] = {
      ...message,
      content: "正在重新获取回复...",
      status: "loading"
    }

    // 重新请求回复
    getAssistantResponse(userMessage, index)
  }
}

// 获取助手回复方法
// 获取助手回复方法
const getAssistantResponse = (message, messageIndex) => {
  // 关闭已有连接
  if (sseSource.value) {
    sseSource.value.close()
  }

  // 清除已有的超时计时器
  if (requestTimeout.value) {
    clearTimeout(requestTimeout.value)
  }

  // 设置超时计时器
  requestTimeout.value = setTimeout(() => {
    if (sseSource.value) {
      sseSource.value.close()
      sseSource.value = null

      // 更新消息状态为错误
      if (messageIndex !== undefined && messages.value[messageIndex]) {
        messages.value[messageIndex] = {
          ...messages.value[messageIndex],
          content: "获取回复超时，请点击重试按钮重新获取",
          status: "error"
        }
      }
    }
  }, timeoutDuration)

  // 获取基础URL
  let baseUrl = '';
  try {
    // 尝试使用Vue3的环境变量
    baseUrl = import.meta.env.VITE_APP_BASE_API || '';
  } catch (e) {
    // 如果失败，尝试使用Vue2的环境变量
    baseUrl = process.env.VUE_APP_BASE_API || '';
  }

  // 确保baseUrl不为空
  if (!baseUrl) {
    console.error('无法获取API基础URL');
    baseUrl = '/api'; // 使用默认值
  }

  // 创建新连接，添加useLocalKnowledge、useHistoryChat和useTools参数
  const apiUrl = baseUrl + "/ai/chat/stream?message=" +
    encodeURIComponent(message) +
    "&useLocalKnowledge=" + useLocalKnowledge.value +
    "&useHistoryChat=" + useHistoryChat.value +
    "&useTools=" + useTools.value;

  sseSource.value = new EventSourcePolyfill(apiUrl, { headers: { 'Authorization': `Bearer ${getToken()}` } })
  // 是否已收到第一条消息
  let receivedFirstMessage = false

  // 监听进度消息
  sseSource.value.addEventListener('chat', (event) => {
    // 收到消息，清除超时计时器
    if (!receivedFirstMessage) {
      receivedFirstMessage = true
      clearTimeout(requestTimeout.value)
      requestTimeout.value = null
    }

    // 获取目标消息
    const targetMessage = messageIndex !== undefined ? messages.value[messageIndex] : messages.value[messages.value.length - 1]

    if (targetMessage && targetMessage.type === 'assistant') {
      // 更新消息状态
      if (targetMessage.status === 'loading' || targetMessage.status === 'error') {
        targetMessage.status = 'success'
        targetMessage.content = ''
      }

      // 判断是否需要添加空格
      const needSpace = targetMessage.content && event.data &&
        /[a-zA-Z]$/.test(targetMessage.content) && // 检查上一段文本是否以英文字母结尾
        /^[a-zA-Z]/.test(event.data)           // 检查新文本是否以英文字母开头

      // 根据判断结果拼接文本
      targetMessage.content += (needSpace ? ' ' : '') + event.data
    }

    // 滚动到底部
    nextTick(() => {
      if (chatMessages.value) {
        chatMessages.value.scrollTop = chatMessages.value.scrollHeight
      }
    })
  })

  // 监听连接关闭
  sseSource.value.addEventListener('done', () => {
    clearTimeout(requestTimeout.value)
    requestTimeout.value = null
    sseSource.value.close()
    sseSource.value = null
  })

  // 监听错误
  sseSource.value.onerror = (error) => {
    console.error('SSE连接错误:', error)
    clearTimeout(requestTimeout.value)
    requestTimeout.value = null
    sseSource.value.close()
    sseSource.value = null

    // 更新消息状态为错误
    if (messageIndex !== undefined && messages.value[messageIndex]) {
      const currentContent = messages.value[messageIndex].content
      // 只有当内容为初始状态或为空时才更新为错误信息
      if (currentContent === '正在思考...' || currentContent === '') {
        messages.value[messageIndex] = {
          ...messages.value[messageIndex],
          content: "连接出错，请点击重试按钮重新获取",
          status: "error"
        }
      }
    }
  }
}

// 组件销毁时清除计时器
onBeforeUnmount(() => {
  if (requestTimeout.value) {
    clearTimeout(requestTimeout.value)
  }
  if (sseSource.value) {
    sseSource.value.close()
  }
})
</script>

<style scoped>
/* 聊天助手基础样式 */
.chat-assistant {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 420px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  transform-origin: bottom right;
  font-size: 16px; /* 全局字体大小 */
}

/* 最小化状态 */
.chat-assistant.minimized {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.chat-assistant.minimized .chat-header {
  height: 100%;
  width: 100%;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  position: relative;
}

.chat-assistant.minimized .chat-header span {
  display: none;
}

.chat-assistant.minimized .header-icons {
  display: none;
}

/* 添加眨眼微笑的人脸图标 */
.chat-assistant.minimized .chat-header:before {
  content: "";
  display: block;
  width: 40px;
  height: 40px;
  background-color: transparent;
  position: relative;
  border-radius: 50%;
}

/* 添加眼睛 */
.chat-assistant.minimized .chat-header:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><circle cx="30" cy="35" r="8" class="eye"><animate attributeName="ry" values="8;1;8" dur="3s" repeatCount="indefinite"/></circle><circle cx="70" cy="35" r="8" class="eye"><animate attributeName="ry" values="8;1;8" dur="3s" repeatCount="indefinite"/></circle><path d="M30,65 Q50,80 70,65" stroke="white" stroke-width="4" fill="none"><animate attributeName="d" values="M30,65 Q50,80 70,65;M30,60 Q50,75 70,60;M30,65 Q50,80 70,65" dur="5s" repeatCount="indefinite"/><animate attributeName="d" values="M30,65 Q50,80 70,65;M30,65 Q50,60 70,65;M30,65 Q50,80 70,65" begin="7s" dur="8s" repeatCount="indefinite"/></path></svg>');
  background-size: 80%;
  background-position: center;
  background-repeat: no-repeat;
  animation: faceAnimation 15s infinite;
}

/* 表情切换动画 */
@keyframes faceAnimation {
  0%, 40% {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><circle cx="30" cy="35" r="8" class="eye"><animate attributeName="ry" values="8;1;8" dur="3s" repeatCount="indefinite"/></circle><circle cx="70" cy="35" r="8" class="eye"><animate attributeName="ry" values="8;1;8" dur="3s" repeatCount="indefinite"/></circle><path d="M30,65 Q50,80 70,65" stroke="white" stroke-width="4" fill="none"/></svg>');
    /* 微笑表情 */
  }
  45%, 47% {
    opacity: 0.8;
  }
  50%, 90% {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><circle cx="30" cy="35" r="8"/><circle cx="70" cy="35" r="8"/><path d="M30,70 Q50,65 70,70" stroke="white" stroke-width="4" fill="none"/><path d="M40,25 L50,20 L60,25" stroke="white" stroke-width="2" fill="none"/></svg>');
    /* 思考表情 */
  }
  95%, 97% {
    opacity: 0.8;
  }
}

/* 眨眼动画 */
@keyframes blinking {
  0%, 45%, 55%, 100% {
    transform: scaleY(1);
  }
  50% {
    transform: scaleY(0.1);
  }
}

/* 添加悬停效果 */
.chat-assistant.minimized:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

/* 全屏状态 */
.chat-assistant.fullscreen {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  border-radius: 0;
  animation: expandFromRight 0.3s ease-out;
}

.chat-assistant.exit-fullscreen {
  animation: shrinkToRight 0.3s ease-in;
}

/* 全屏动画 */
@keyframes expandFromRight {
  0% {
    transform: scale(0.3);
    opacity: 0.7;
    right: 20px;
    bottom: 20px;
    top: auto;
    left: auto;
    width: 420px;
    height: 480px;
  }

  100% {
    transform: scale(1);
    opacity: 1;
    right: 0;
    bottom: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

@keyframes shrinkToRight {
  0% {
    transform: scale(1);
    opacity: 1;
    right: 0;
    bottom: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }

  100% {
    transform: scale(0.3);
    opacity: 0.7;
    right: 20px;
    bottom: 20px;
    top: auto;
    left: auto;
    width: 420px;
    height: 480px;
  }
}

/* 聊天头部样式 */
.chat-header {
  padding: 10px 15px;
  background-color: #409EFF;
  color: white;
  border-radius: 8px 8px 0 0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}

.chat-assistant.fullscreen .chat-header {
  border-radius: 0;
}

.header-icons {
  display: flex;
  align-items: center;
}

.header-icons i {
  margin-left: 10px;
  cursor: pointer;
}

/* 聊天主体样式 */
.chat-body {
  display: flex;
  flex-direction: column;
  height: 480px;
}

.chat-assistant.fullscreen .chat-body {
  height: calc(100% - 40px);
}

/* 消息区域样式 */
.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

/* 消息样式 */
.message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
}

.user-message {
  align-items: flex-end;
}

.assistant-message {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 6px;
  word-break: break-word;
  font-size: 16px;
}

.user-message .message-content {
  background-color: #409EFF;
  color: white;
}

/* 用户消息样式 */
.user-content {
  max-width: 90%;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.user-md-body {
  background-color: #1890ff; /* 更鲜亮的蓝色 */
  background-image: linear-gradient(135deg, #1890ff, #096dd9); /* 添加渐变效果 */
  color: #ffffff;
  text-align: left;
  max-width: 100%;
  overflow: hidden;
  font-weight: 500;
  text-shadow: 0 0 1px rgba(0, 0, 0, 0.2);
  border-radius: 12px 12px 0 12px; /* 现代化的圆角设计 */
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3); /* 添加阴影效果 */
}

/* 助手消息样式 */
.assistant-content {
  max-width: 90%;
  width: 100%;
  overflow: hidden;
}

/* Markdown 内容样式 */
.md-body {
  background-color: #ffffff; /* 改为白色背景 */
  border-radius: 12px 12px 12px 0; /* 现代化的圆角设计，与用户消息相反 */
  padding: 12px 16px; /* 增加内边距 */
  text-align: left;
  font-size: 14px;
  line-height: 1.2;
  max-width: 100%;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: normal;
  box-sizing: border-box;
  overflow: hidden;
  color: #333333;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); /* 轻微阴影 */
  border: 1px solid #f0f0f0; /* 添加细边框 */
}

/* Markdown 元素样式 */
.md-body pre {
  background-color: #f6f8fa;
  border-radius: 6px; /* 增加代码块圆角 */
  padding: 16px;
  overflow: auto;
  max-width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
  border-left: 3px solid #1890ff; /* 添加左侧边框，增加设计感 */
}

.md-body code {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 14px;
  word-break: break-all;
  color: #333333; /* 确保代码文本颜色足够深 */
}

.md-body a {
  word-break: break-all;
  overflow-wrap: break-word;
}

.md-body img {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
  margin: 5px 0;
  display: block;
}

.md-body table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
  font-size: 15px;
  display: block;
  overflow-x: auto;
  max-width: 100%;
}

.md-body th,
.md-body td {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
  word-break: break-word;
}

/* 消息操作区域样式 */
.message-actions {
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.assistant-message .message-actions {
  justify-content: flex-start;
}

.message-actions .el-button {
  padding: 2px 5px;
  font-size: 14px;
}

.message-actions .el-button+.el-button {
  margin-left: 5px;
}

/* 输入区域样式 */
.chat-input {
  padding: 10px;
  border-top: 1px solid #eee;
}

/* 知识库开关样式 */
.knowledge-switch {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #606266;
}

.knowledge-switch span {
  margin-right: 10px;
}

/* 图片预览区域样式 */
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.image-preview-item {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  padding: 2px;
  cursor: pointer;
  font-size: 12px;
}

/* 快捷操作区域样式 */
.quick-actions {
  display: flex;
  justify-content: space-around;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.quick-actions .el-button {
  margin: 0 2px;
  font-size: 14px;
}

/* Element Plus 样式覆盖 */
.el-input__inner {
  font-size: 16px !important;
}
</style>
